<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Resources\Admin\Machines;
use App\Http\Resources\Admin\Machine as MachineResource;
use App\Models\Machine;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;

class MachinesController extends Controller
{
    /**
     * 游戏机列表
     *
     * @param Request $request
     * @return Machines
     */
    public function index(Request $request)
    {
        $perPage = per_page();

        $filter = [];
        if ($request->filled('device_sn')) {
            $filter['device_sn'] = $request->get('device_sn');
        }

        $paginate = Machine::where($filter)->orderByDesc('stick_time')->orderByDesc('id')->paginate($perPage);

        return new Machines($paginate);
    }

    /**
     * 游戏机更新
     *
     * @param Request $request
     * @param \App\Models\Machine $machine
     */
    public function update(Request $request, Machine $machine)
    {
        $inputs = $this->validate($request, [
            'is_display' => 'in:0,1',
            'is_top' => 'in:0,1',
            'name' => 'string|max:30',
            'ware_name' => 'string|max:30',
            'coin' => 'integer|between:1,9999',
            'detail_image_file' => 'image',
            'ware_image_file' => 'image',
        ]);

        if (isset($inputs['is_top']) && $inputs['is_top'] == 1) {
            $inputs['stick_time'] = time();
            unset($inputs['is_top']);
        }

        unset($inputs['detail_image_file']);
        unset($inputs['ware_image_file']);

        // 详情图
        if ($request->hasFile('detail_image_file')) {
            $path = upload_image('detail_image_file');

            // 删除旧的详情图
            if ($machine->detail_image) {
                Storage::delete($machine->detail_image);
            }
            
            $machine->detail_image = $path;
        }

        // 商品图
        if ($request->hasFile('ware_image_file')) {
            $path = upload_image('ware_image_file');
            $machine->ware_image = image_url($path);
        }

        $machine->update($inputs);
    }

    /**
     * 游戏机详情
     *
     * @param \App\Models\Machine $machine
     * @return \App\Http\Resources\Admin\Machine
     */
    public function show(Machine $machine)
    {
        return new MachineResource($machine);
    }

    /**
     * 同步设备
     */
    public function sync()
    {
        Artisan::call('mall:doll-sync');
    }
}
